﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using V5_BLL;
using V5_Common;
using V5_Model;

namespace V5_EShop.Controllers {
    public class OrderController : BaseController {

        #region 购物车
        // 购物车
        public ActionResult Cart() {
            return View();
        }

        //购物车Post
        public ContentResult CartPost() {
            return Content("处理成功!");
        }

        public int shopping_pro_count = 0;
        public int shopping_price_count = 0;
        public int shopping_pro_score = 0;

        private void Bind_EditShopping(int proid) {
            string txtQuantity = InputHelper.SetString(Request["txtQuantity"]);
            shopping shop = new shopping();
            DataTable dtProducts = null;
            int m1 = 0, m2 = 0, m3 = 0, m4 = 0, m6 = 0;
            string jsonstr = "";
            if (Session["dtProducts"] == null) { }
            else {
                dtProducts = (DataTable)Session["dtProducts"];
                if (dtProducts != null && dtProducts.Rows.Count > 0) {
                    m6 = 0;
                    DataRow[] DataRows = dtProducts.Select(" pid=" + proid);
                    ModelProduct model = new BLLProduct().GetModel(proid, true);
                    //判断 是否超过库存
                    if (InputHelper.SetInt(txtQuantity) > model.ProductCount) {
                        return;
                    }
                    //计算
                    foreach (DataRow item1 in DataRows) {
                        // item1["pid"] = proid;
                        item1["prototalprice"] = (InputHelper.SetInt(model.ProductMemberPrice) * InputHelper.SetInt(txtQuantity));//小计
                        // item1["promemberprice"] = model.ProductMemberPrice;
                        //item1["promarketprice"] = model.ProductMarketPrice;
                        item1["proquantity"] = txtQuantity;
                        // item1["profieldvalues"] = txtfieldvalues;
                        //item1["proname"] = model.ProductName;
                        //item1["propic"] = model.ProductBigPic;
                        //item1["quantity"] = dtProducts.Rows.Count + 1;
                    }
                    dtProducts.AcceptChanges();
                    //    //开始计算
                    //小计价格 m2
                    m2 = (InputHelper.SetInt(model.ProductMemberPrice) * InputHelper.SetInt(txtQuantity));
                    m1 = m2;//赠送积分
                    m3 = dtProducts.Rows.Count;//管理数量
                    //产品总金额
                    for (int i = 0; i < dtProducts.Rows.Count; i++) {
                        m6 += (InputHelper.SetInt(dtProducts.Rows[i]["prototalprice"]));
                    }
                    m4 = m6;//积分总计
                    //    //计算结束
                    Session["dtProducts"] = dtProducts;//修改完毕后更新session

                    shop.i1 = m2;
                    shop.i2 = m2;
                    shop.i3 = m3;
                    shop.i4 = m6;
                    shop.i5 = 5;
                    shop.i6 = m6;
                    jsonstr = JsonConvert.SerializeObject(shop);
                    Response.Write(jsonstr);
                    Response.End();
                }
                Response.End();
            }
        }
        class shopping {
            public int i1;//赠送积分
            public int i2;//小计价格
            public int i3;//管理数量总计
            public int i4;//赠送积分总计
            public int i5;//花费积分总计
            public int i6;//产品金额总计
        }
        //添加购物
        private void Bind_addshoppingcart(int proid) {
            string txtfieldvalues = InputHelper.SetString(Request["txtfieldvalues"]);
            string txtQuantity = InputHelper.SetString(Request["txtQuantity"]);
            if (proid > 0) {
                ModelProduct model = new BLLProduct().GetModel(proid, true);
                if (model != null) {
                    DataTable dtProducts = null;
                    if (Session["dtProducts"] == null) {
                        dtProducts = new DataTable();
                        dtProducts.Columns.Add(new DataColumn("pid"));//产品ID
                        dtProducts.Columns.Add(new DataColumn("prototalprice"));//总价格
                        dtProducts.Columns.Add(new DataColumn("promemberprice"));//会员价
                        dtProducts.Columns.Add(new DataColumn("promarketprice"));//市场价 
                        dtProducts.Columns.Add(new DataColumn("proquantity"));//单个产品数量
                        dtProducts.Columns.Add(new DataColumn("profieldvalues"));//产品规格
                        dtProducts.Columns.Add(new DataColumn("proname"));//产品名称
                        dtProducts.Columns.Add(new DataColumn("propic"));//产品图片
                        dtProducts.Columns.Add(new DataColumn("proscore"));//增送积分
                    }
                    else {
                        dtProducts = (DataTable)Session["dtProducts"];
                    }
                    //添加产品
                    bool found = false;
                    //循环购物车 是否有重复的产品
                    for (int i = 0; i < dtProducts.Rows.Count; i++) {
                        if (Convert.ToInt32(dtProducts.Rows[i]["pid"]) == proid) {
                            found = true;
                            break;
                        }
                    }
                    //如果购物车没有产品 开始添加
                    if (!found) {
                        DataRow aProduct = dtProducts.NewRow();

                        aProduct["pid"] = proid;
                        aProduct["prototalprice"] = (InputHelper.SetInt(model.ProductMemberPrice) * InputHelper.SetInt(txtQuantity));//小计
                        aProduct["promemberprice"] = model.ProductMemberPrice;
                        aProduct["promarketprice"] = model.ProductMarketPrice;
                        aProduct["proquantity"] = txtQuantity;
                        aProduct["profieldvalues"] = txtfieldvalues;
                        aProduct["proname"] = model.ProductName;
                        aProduct["propic"] = model.ProductBigPic;
                        aProduct["proscore"] = InputHelper.SetInt(model.ProductMemberPrice);//赠送积分
                        dtProducts.Rows.Add(aProduct);
                    }
                    Session["dtProducts"] = dtProducts;//添加完毕后更新session
                    //管理数量
                    shopping_pro_count = dtProducts.Rows.Count;
                    //管理总金额
                    for (int i = 0; i < dtProducts.Rows.Count; i++) {
                        shopping_price_count += InputHelper.SetInt(dtProducts.Rows[i]["prototalprice"]);
                    }
                    //积分
                    shopping_pro_score = shopping_price_count;
                    /*
                    Repeater rp = (Repeater)this.FindControl("rpShoppingcartList");
                    if (rp != null) {
                        rp.DataSource = dtProducts;
                        rp.DataBind();
                    }*/
                }
            }
            else {
                DataTable dtProducts = null;
                if (Session["dtProducts"] != null) {
                    dtProducts = (DataTable)Session["dtProducts"];
                    /*
                    Repeater rp = (Repeater)this.FindControl("rpShoppingcartList");
                    if (rp != null) {
                        rp.DataSource = dtProducts;
                        rp.DataBind();
                    }*/
                }
            }
        }

        private void Bind_delshoppingitem(int proid) {
            if (proid > 0) {
                ModelProduct model = new BLLProduct().GetModel(proid, true);
                if (model != null) {
                    DataTable dtProducts = null;
                    if (Session["dtProducts"] != null) {
                        dtProducts = (DataTable)Session["dtProducts"];
                    }
                    else {
                        Response.Redirect(HttpHelper.ComeUrl);
                    }

                    for (int i = 0; i < dtProducts.Rows.Count; i++) {
                        if (Convert.ToInt32(dtProducts.Rows[i]["pid"]) == proid) {
                            dtProducts.Rows[i].Delete();
                        }
                    }
                    dtProducts.AcceptChanges();
                    Session["dtProducts"] = dtProducts;//添加完毕后更新session
                    //
                    //管理数量
                    shopping_pro_count = dtProducts.Rows.Count;
                    //管理总金额
                    for (int i = 0; i < dtProducts.Rows.Count; i++) {
                        shopping_price_count += InputHelper.SetInt(dtProducts.Rows[i]["prototalprice"]);
                    }
                    //积分
                    shopping_pro_score = shopping_price_count;
                    /*
                    Repeater rp = (Repeater)this.FindControl("rpShoppingcartList");
                    if (rp != null) {
                        rp.DataSource = dtProducts;
                        rp.DataBind();
                    }*/
                    //
                }
            }
        }
        #endregion

        //地址
        public ActionResult Address() {
            DataTable dt = new BLLUserToArea().GetList(3, " UserID=" + 0, " ID Desc").Tables[0];
            this.ViewData["list"] = dt.Rows;
            return View();
        }

        //地址Post
        public ContentResult AddressPost() {
            //开始保存地址
            string action = Request["action"];
            int id = InputHelper.SetInt(Request.Form["hfid"]);

            if (action == "del") {
                new BLLUserToArea().Delete(id);
                return Content("配货地址删除成功!");
            }

            int userid = 0;
            string ToUserName = Request["ToUserName"];
            string Provinces = InputHelper.SetString(Request["province"]);
            string Cities = InputHelper.SetString(Request["City"]);
            string Counties = InputHelper.SetString(Request["County"]);
            string UserToUrl = InputHelper.SetString(Request["UserToUrl"]);
            string UserToPostNum = Request["UserToPostNum"];
            string UserToPhone = Request["UserToPhone"];
            string ToUserTelePhone = Request["ToUserTelePhone"];

            BLLUserToArea bll = new BLLUserToArea();
            ModelUserToArea model = new ModelUserToArea();
            model.tousername = ToUserName;
            model.touserareapro = Provinces;
            model.touserareacity = Cities;
            model.touserareacity2 = Counties;
            model.touserurl = UserToUrl;
            model.topostnum = UserToPostNum;
            model.touserphone = UserToPhone;
            model.tousertelephone = ToUserTelePhone;
            model.adddatetime = DateTime.Now;
            model.userid = userid;
            if (id == 0) {
                //检查一下最大的个数
                int count = bll.GetList(" userid=" + 0).Tables[0].Rows.Count;
                if (count < 4) {
                    int _id = bll.GetMaxId();
                    model.id = _id;
                    bll.Add(model);
                    Response.Redirect("/Shopping_pay.aspx?addressid=" + _id);
                }
                else {
                    return Content("您的可用地址已经满了!请删除一个在添加!");
                }
            }
            else if (id > 0) {
                model.id = id;
                bll.Update(model);
                Response.Redirect("/Shopping_pay.aspx?addressid=" + id);
            }
            return Content("处理成功!");
        }

        public ActionResult Order() {
            return View();
        }

        public ContentResult OrderPost() {

            var OtherContent = Request["OtherContent"];
            var payid = 0;
            var sendid = 0;
            var FaStartTitle = Request["FaStartTitle"];

            var user = new ModelUser();
            var area = new ModelUserToArea();
            //检查购物车是否为空
            if (Session["dtProducts"] == null) {
                return Content("购物车没有产品!");
            }
            DataTable dt = (DataTable)Session["dtProducts"];
            int m_TotalPrice = 0;//产品总价
            int m_productcount = 0;//产品个数
            for (int i = 0; i < dt.Rows.Count; i++) {
                m_TotalPrice = m_TotalPrice + InputHelper.SetInt(dt.Rows[i]["prototalprice"].ToString());
            }
            m_productcount = dt.Rows.Count;

            BLLProductOrder bll = new BLLProductOrder();
            ModelProductOrder model = new ModelProductOrder();
            int OrderID = 0;
            //配送方式
            //送货地址

            //支付方式
            //送货时间
            /**/
            int MemberID = user.ID;//会员ID号
            DateTime OrderTime = DateTime.Now;//订单时间
            string ShipTime = sendid.ToString();//送货时间
            string BuyerName = user.TrueName;//买家用户名
            string BuyerPhone = user.Telephone;//买家电话
            string BuyerEmail = user.UserEmail;//买家Email
            string BuyerAddress = user.Address;//买家地址
            string BuyerPostalcode = user.AreaID.ToString();//邮政编号
            string ReceiverName = area.tousername;//收货人姓名
            string ReceiverPhone = area.tousertelephone;//收货人电话
            string ReceiverEmail = user.UserEmail;//收货人Email
            string ReceiverAddress = area.id.ToString();//配货地址ID号
            string ReceiverPostalcode = area.topostnum;//收货人邮政编号
            string Remark = OtherContent;//订单备注
            decimal TotalPrice = m_TotalPrice;//产品总价
            decimal ProductPrice = 20;//产品价格
            decimal CustomItemPrice = 200;//自定义价格
            string Discount = "20%";//折扣
            decimal ShipPrice = 0;//邮费
            decimal AdvancePayment = 100;//高级付款
            int PaymentType = payid;//支付类型
            int ShippingType = sendid;//送货类型
            int Score = m_TotalPrice;//积分
            decimal Weight = 100;//重量
            int Quantity = m_productcount;//个数
            //Response.Write(Input.SetString(Request.Form["fapiao"]));
            int NeedInvoice = 0;//需要发票
            string InvoiceHead = FaStartTitle;//发票头
            string InvoiceContent = "";//发票头
            //if (rbtnfa1.Checked) {
            //    NeedInvoice = 1;
            //    InvoiceContent = "";
            //}
            //if (rbtnfa2.Checked) {
            //    NeedInvoice = 0;
            //    InvoiceContent = "无";
            //}


            int IsCancelled = 1;//取消
            int IsConfirmed = 1;//确认
            int PayStatus = 0;//支付状态 0 未支付 1 支付
            int ShippingStatus = 0;//订单状态 0 添加 1 已确认 2 已付款 3已发货 4 已归档 5 取消订单 
            int IsFinished = 0;//完成
            string ManageHistory = "收货";
            int LastModify = 1;
            string OrderNo = bll.ProductOrderNum();//订单号
            string Code = OtherContent;//代码
            int IsAgentF = 1;
            string IsAgentFContent = "恩";
            int IsShippingFree = 1;//是否订单免邮费
            //************************************************************************************
            //************************************************************************************
            //开始保存订单 并生产订单
            model.MemberID = MemberID;
            model.OrderTime = OrderTime;
            model.ShipTime = ShipTime;
            model.BuyerName = BuyerName;
            model.BuyerPhone = BuyerPhone;
            model.BuyerEmail = BuyerEmail;
            model.BuyerAddress = BuyerAddress;
            model.BuyerPostalcode = BuyerPostalcode;
            model.ReceiverName = ReceiverName;
            model.ReceiverPhone = ReceiverPhone;
            model.ReceiverEmail = ReceiverEmail;
            model.ReceiverAddress = ReceiverAddress;
            model.ReceiverPostalcode = ReceiverPostalcode;
            model.Remark = Remark;
            model.TotalPrice = TotalPrice;
            model.ProductPrice = ProductPrice;
            model.CustomItemPrice = CustomItemPrice;
            model.Discount = Discount;
            model.ShipPrice = ShipPrice;
            model.AdvancePayment = AdvancePayment;
            model.PaymentType = PaymentType;
            model.ShippingType = ShippingType;
            model.Score = Score;
            model.Weight = Weight;
            model.Quantity = Quantity;
            model.NeedInvoice = NeedInvoice;
            model.InvoiceHead = InvoiceHead;
            //
            model.InvoiceContent = InvoiceContent;
            model.IsCancelled = IsCancelled;
            model.IsConfirmed = IsConfirmed;
            model.PayStatus = PayStatus;
            model.ShippingStatus = ShippingStatus;
            model.IsFinished = IsFinished;
            model.ManageHistory = ManageHistory;
            model.LastModify = LastModify;
            model.OrderNo = OrderNo;
            model.Code = Code;
            model.IsAgentF = IsAgentF;
            model.IsAgentFContent = IsAgentFContent;
            model.IsShippingFree = IsShippingFree;
            OrderID = bll.Add(model);
            //开始清空购物车
            if (Session["dtProducts"] != null) {
                //开始添加产品信息
                DataTable dt1 = (DataTable)Session["dtProducts"];
                foreach (DataRow row in dt1.Rows) {
                    ModelProductOrderProduct m_ProductOrderProduct = new ModelProductOrderProduct();
                    m_ProductOrderProduct.ID = new BLLProductOrderProduct().GetMaxId();
                    m_ProductOrderProduct.OrderNum = model.OrderNo;//订单号
                    m_ProductOrderProduct.pid = InputHelper.SetInt(row["pid"]);
                    m_ProductOrderProduct.profieldvalues = InputHelper.SetString(row["profieldvalues"]);
                    m_ProductOrderProduct.promarketprice = InputHelper.SetInt(row["promarketprice"]);
                    m_ProductOrderProduct.promemberprice = InputHelper.SetInt(row["promemberprice"]);
                    m_ProductOrderProduct.proname = InputHelper.SetString(row["proname"]);
                    m_ProductOrderProduct.propic = InputHelper.SetString(row["propic"]);
                    m_ProductOrderProduct.proquantity = InputHelper.SetInt(row["proquantity"]);
                    m_ProductOrderProduct.proscore = InputHelper.SetInt(row["proscore"]);
                    m_ProductOrderProduct.prototalprice = InputHelper.SetInt(row["prototalprice"]);
                    new BLLProductOrderProduct().Add(m_ProductOrderProduct);
                }
                //清空购物车
                Session.Remove("dtProducts");
            }
            //发送Email
            Response.Redirect("/Shopping_Clearing.aspx?OrderID=" + OrderID + "&BEmail=" + user.UserEmail);

            return Content("处理成功!");
        }

        //支付
        public ActionResult Pay() {
            return View();
        }

        //支付Post
        public ActionResult PayPost() {
            return View();
        }

        public ActionResult Result() {
            var _OrderID = InputHelper.SetInt(Request["OrderID"]);
            var _BEmail = InputHelper.SetString(Request["BEmail"]);
            if (_OrderID > 0) {
                var order = new BLLProductOrder().GetModel(_OrderID);
                this.ViewData["order"] = order; 
            }
            return View();
        }
    }
}